package x.trident.core.config.center.manager;

import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import x.trident.core.config.center.context.NacosConfigContext;
import x.trident.core.config.center.inject.InjectFunc;

import java.lang.reflect.Field;
import java.util.concurrent.Executor;

/**
 * 配置管理
 *
 * @author 林选伟
 * @date 2021/9/3 11:23 上午
 */
@Component
@Slf4j
public class ConfigManager {
    /**
     * 拉取配置
     *
     * @param dataId 配置的key
     * @return 值
     * @throws NacosException 异常
     */
    public Object getValue(String dataId) throws NacosException {
        return NacosConfigContext.getConfigService().getConfig(dataId, NacosConfigContext.getGroup(), 2000);
    }

    /**
     * 发布配置
     *
     * @param dataId  配置的key
     * @param content 配置内容
     * @return 是否发布成功
     * @throws NacosException 异常
     */
    public boolean publish(String dataId, String content) throws NacosException {
        return NacosConfigContext.getConfigService().publishConfig(dataId, NacosConfigContext.getGroup(), content);
    }

    /**
     * 监听配置变更
     *
     * @param dataId 配置key
     * @throws NacosException 异常
     */
    public void addListener(String dataId, InjectFunc injectFunc, Object bean, Field field) throws NacosException {
        NacosConfigContext.getConfigService().addListener(dataId, NacosConfigContext.getGroup(), new Listener() {
            @SneakyThrows
            @Override
            public void receiveConfigInfo(String newConfig) {
                log.debug("监听到配置发生变更:{}, 新的配置是:{}", dataId, newConfig);
                injectFunc.inject(bean, field, newConfig);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });
    }

}
